package com.example.mykotilin.paging

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.*
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map

class CheeseViewModel(private val cheeseDao: CheeseDao) : ViewModel() {
    val allCheeses: Flow<PagingData<CheeseListItem>> = Pager(
        config = PagingConfig(
            pageSize = 60,
            enablePlaceholders = true, maxSize = 200
        )
    ) {
        cheeseDao.allCheesesByName()  //查询所有的数据
    }.flow.map { pagingData ->
        pagingData.map {
            //将cheese转换为CheeseListItem
                cheese -> CheeseListItem.Item(cheese) }
            .insertSeparators {
                    //插入分割符号
                    before: CheeseListItem?, after: CheeseListItem? ->
                if (before == null && after == null) {
                    null
                } else if (after == null) {
                    null
                } else if (before == null) {
                    CheeseListItem.Separator(after.name.first())
                } else if (!before.name.first().equals(after.name.first(), ignoreCase = true)) {
                    CheeseListItem.Separator(after.name.first())
                } else {
                    null
                }
            }
    }
        .cachedIn(viewModelScope)

    fun insert(text: CharSequence) = ioThread {
        cheeseDao.insert(Cheese(id = 0, name = text.toString()))
    }

    fun remove(cheese: Cheese) = ioThread {
        cheeseDao.delete(cheese)
    }
}